package com.shiyi.design.iterator;

import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * @author wangzhanshuai
 * @date 2021/2/5 6:30 下午
 * @since 1.0
 */
public class ArrayListImpl<E> implements ListInterface<E> {

    private Object[] elements;

    private static final Object[] EMPTY_ELEMENTS = {};

    private int size;


    public ArrayListImpl() {
        this.elements = EMPTY_ELEMENTS;
    }

    public ArrayListImpl(int size) {
        if (size > 0) {
            this.elements = new Object[size];
        } else if (size == 0) {
            this.elements = EMPTY_ELEMENTS;
        } else {
            throw new RuntimeException("contain init fair");
        }
    }

    @Override
    public void add(E e) {
        int max = size + 1;
        if (elements == EMPTY_ELEMENTS) {
            max = Math.max(10, size + 1);
        }
        if (max - elements.length > 0) {
            int oldLength = elements.length;
            int newLength = oldLength + (oldLength >> 1);
            if (newLength - max < 0) {
                newLength = max;
            }
            elements = Arrays.copyOf(elements, newLength);
        }
        elements[size++] = e;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public IteratorInterface<E> iterator() {
        return new ArrayListIterator();
    }

    private class ArrayListIterator implements IteratorInterface<E> {
        private int modCount;

        @Override
        public boolean hasNext() {
            return modCount < size;
        }

        @Override
        public E next() {
            if(!hasNext()) {
                throw new RuntimeException("value is out");
            }
            return (E) elements[modCount++];
        }
    }
}
